<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

defined('IN_COMPONENT_CONTROLLER') or die();

class OrderComponent
{
	function OrderComponent()
	{
	}

	function action(&$params, $action)
	{
		if ($action == 'Download') 
			return $this->download($params);
		else 
			return $this->query($params);
	}

	function query(&$params) 
	{
		$language_id = (int)$params['languageId'];
		$accountId = (int)$params['accountId'];
		$isAdministrator = (boolean)$params['isAdministrator'];
		$orderId = (int)$params['orderId'];
		$value{'OrderComponentMetaData'}{'display_company'}= returnBoolean(ACCOUNT_COMPANY);
		$value{'OrderComponentMetaData'}{'display_state'}= returnBoolean(ACCOUNT_STATE);
		$value{'OrderComponentMetaData'}{'display_suburb'}= returnBoolean(ACCOUNT_SUBURB);

		if ($accountId > 0 && $orderId > 0)
		{
			$sqlQuery = 'select o.orders_id, o.customers_name, o.customers_company, o.customers_street_address, o.customers_suburb, o.customers_city, ' .
			'o.customers_postcode, o.customers_state, o.customers_country, o.customers_telephone, o.customers_email_address, ' .
			'o.delivery_name, o.delivery_company, o.delivery_street_address, o.delivery_suburb, o.delivery_city, o.delivery_postcode, o.delivery_state, ' .
			'o.delivery_country, o.billing_name, o.billing_company, o.billing_street_address, o.billing_suburb, o.billing_city, o.billing_postcode, ' . 
			"o.billing_state, o.billing_country, o.payment_method, DATE_FORMAT(o.last_modified, '%Y-%m-%d %H:%i:%s') as last_modified, " .
			"DATE_FORMAT(o.date_purchased, '%Y-%m-%d %H:%i:%s') as date_purchased, os.orders_status_name, o.currency, o.currency_value, ot.value " .
			'from ' . TABLE_ORDERS . ' o, ' . TABLE_ORDERS_STATUS . ' os, ' . TABLE_ORDERS_TOTAL . ' ot ' .
			'where o.orders_id = \''. $orderId . '\' ';

			if (!$isAdministrator) $sqlQuery .= 'and customers_id = \''. $accountId .'\' ';

			$sqlQuery .= 'and o.orders_status = os.orders_status_id ' .
			'and o.orders_id = ot.orders_id and ot.class = \'ot_total\' ' .
			'and os.language_id = \'' . $language_id . '\' and o.orders_status > -1';
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			$i = 0;

			while($row = mysql_fetch_array($dataReturned))
			{
				$order_id = (int)$row['orders_id'];
				$value{'OrderComponent'}{$i}{'id'}= $order_id;
				$value{'OrderComponent'}{$i}{'name'}= $row['customers_name'];
				$value{'OrderComponent'}{$i}{'company'}= $row['customers_company'];
				$value{'OrderComponent'}{$i}{'street_address'}= $row['customers_street_address'];
				$value{'OrderComponent'}{$i}{'suburb'}= $row['customers_suburb'];
				$value{'OrderComponent'}{$i}{'city'}= $row['customers_city'];
				$value{'OrderComponent'}{$i}{'postcode'}= $row['customers_postcode'];
				$value{'OrderComponent'}{$i}{'state'}= $row['customers_state'];
				$value{'OrderComponent'}{$i}{'country'}= $row['customers_country'];
				$value{'OrderComponent'}{$i}{'telephone'}= $row['customers_telephone'];
				$value{'OrderComponent'}{$i}{'email_address'}= $row['customers_email_address'];
				$value{'OrderComponent'}{$i}{'ship_to_name'}= $row['delivery_name'];
				$value{'OrderComponent'}{$i}{'ship_to_company'}= $row['delivery_company'];
				$value{'OrderComponent'}{$i}{'ship_to_street_address'}= $row['delivery_street_address'];
				$value{'OrderComponent'}{$i}{'ship_to_suburb'}= $row['delivery_suburb'];
				$value{'OrderComponent'}{$i}{'ship_to_city'}= $row['delivery_city'];
				$value{'OrderComponent'}{$i}{'ship_to_postcode'}= $row['delivery_postcode'];
				$value{'OrderComponent'}{$i}{'ship_to_state'}= $row['delivery_state'];
				$value{'OrderComponent'}{$i}{'ship_to_country'}= $row['delivery_country'];
				$value{'OrderComponent'}{$i}{'bill_to_name'}= $row['billing_name'];
				$value{'OrderComponent'}{$i}{'bill_to_company'}= $row['billing_company'];
				$value{'OrderComponent'}{$i}{'bill_to_street_address'}= $row['billing_street_address'];
				$value{'OrderComponent'}{$i}{'bill_to_suburb'}= $row['billing_suburb'];
				$value{'OrderComponent'}{$i}{'bill_to_city'}= $row['billing_city'];
				$value{'OrderComponent'}{$i}{'bill_to_postcode'}= $row['billing_postcode'];
				$value{'OrderComponent'}{$i}{'bill_to_state'}= $row['billing_state'];
				$value{'OrderComponent'}{$i}{'bill_to_country'}= $row['billing_country'];
				$value{'OrderComponent'}{$i}{'payment_method'}= $row['payment_method'];
				$value{'OrderComponent'}{$i}{'last_modified'}= $row['last_modified'];
				$value{'OrderComponent'}{$i}{'date_purchased'}= $row['date_purchased'];
				$value{'OrderComponent'}{$i}{'status'}= $row['orders_status_name'];
				$value{'OrderComponent'}{$i}{'currency_code'}= $row['currency'];
				$value{'OrderComponent'}{$i}{'currency_value'}= (double)$row['currency_value'];
				$value{'OrderComponent'}{$i}{'value'}= (double)$row['value'];

				$sqlQuery1 = 'select ot.title, ot.value, ot.class ' .
				' from ' . TABLE_ORDERS_TOTAL . ' ot ' .
				'where ot.orders_id = \''. $order_id . '\' ' .
				'order by ot.sort_order';

				$dataReturned1 = mysql_query($sqlQuery1) or die(mysql_error());
				$i1 = 0;
				while($row1 = mysql_fetch_array($dataReturned1))
				{
					$value{'OrderComponent'}{$i}{'totals'}{$i1}{'title'}= $row1['title'];
					$value{'OrderComponent'}{$i}{'totals'}{$i1}{'value'}= (double)$row1['value'];
					$value{'OrderComponent'}{$i}{'totals'}{$i1}{'class'}= $row1['class'];
					$i1++;
				}

				$sqlQuery1 = "select os.orders_status_name, DATE_FORMAT(osh.date_added, '%Y-%m-%d %H:%i:%s') as date_added, osh.comments" .
				' from ' . TABLE_ORDERS_STATUS_HISTORY . ' osh, ' . TABLE_ORDERS_STATUS . ' os ' .
				'where osh.orders_id = \''. $order_id . '\' ' .
				'and osh.orders_status_id = os.orders_status_id ' .
				'and osh.customer_notified = 1 ' .
				'order by osh.orders_status_history_id';

				$dataReturned1 = mysql_query($sqlQuery1) or die(mysql_error());
				$i1 = 0;
				while($row1 = mysql_fetch_array($dataReturned1))
				{
					$value{'OrderComponent'}{$i}{'histories'}{$i1}{'status'}= $row1['orders_status_name'];
					$value{'OrderComponent'}{$i}{'histories'}{$i1}{'date_added'}= $row1['date_added'];				
					$value{'OrderComponent'}{$i}{'histories'}{$i1}{'comments'}= nl2br($row1['comments']);
					$i1++;
				}

				$sqlQuery1 = 'select op.orders_products_id, op.products_id, op.products_model, op.products_name, ' .
				'op.products_price, op.final_price, op.products_tax, op.products_quantity' .
				' from ' . TABLE_ORDERS_PRODUCTS . ' op ' .
				'where op.orders_id = \''. $order_id . '\' ' .
				'order by op.products_name, op.orders_products_id';

				$dataReturned1 = mysql_query($sqlQuery1) or die(mysql_error());
				$i1 = 0;
				while($row1 = mysql_fetch_array($dataReturned1))
				{
					$opId = (int)$row1['orders_products_id'];
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'op_id'}= $opId;
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'id'}= (int)$row1['products_id'];
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'model'}= $row1['products_model'];				
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'name'}= $row1['products_name'];			
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'base_price'}= (double)$row1['products_price'];		
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'final_price'}= (double)$row1['final_price'];		
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'tax'}= (double)$row1['products_tax'];		
					$value{'OrderComponent'}{$i}{'products'}{$i1}{'quantity'}= (double)$row1['products_quantity'];

					$sqlQuery2 = 'select opa.products_options, opa.products_options_values, opa.options_values_price, opa.price_prefix' .
					' from ' . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . ' opa ' .
					'where opa.orders_id = \'' . $orderId . '\' ' .
					'and opa.orders_products_id = \'' . $opId . '\' ' .
					'order by opa.orders_products_attributes_id';

					$dataReturned2 = mysql_query($sqlQuery2) or die(mysql_error());
					$i2 = 0;
					while($row2 = mysql_fetch_array($dataReturned2))
					{
						$value{'OrderComponent'}{$i}{'products'}{$i1}{'attributes'}{$i2}{'id'}= 0;
						$value{'OrderComponent'}{$i}{'products'}{$i1}{'attributes'}{$i2}{'values_id'}= 0;
						$value{'OrderComponent'}{$i}{'products'}{$i1}{'attributes'}{$i2}{'name'}= $row2['products_options'];
						$value{'OrderComponent'}{$i}{'products'}{$i1}{'attributes'}{$i2}{'values_name'}= $row2['products_options_values'];
						$value{'OrderComponent'}{$i}{'products'}{$i1}{'attributes'}{$i2}{'values_price'}= (double)$row2['options_values_price'];
						$value{'OrderComponent'}{$i}{'products'}{$i1}{'attributes'}{$i2}{'values_price_prefix'}= $row2['price_prefix'];
						$i2++;
					}

					// Download
					$sqlQuery2 = "select date_format(o.date_purchased, '%Y-%m-%d')" . ' as date_purchased_day, opd.download_count, ' .
					'opd.download_maxdays, opd.orders_products_filename, opd.orders_products_download_id ' . 
					'from ' . TABLE_ORDERS . ' o, ' . TABLE_ORDERS_PRODUCTS . ' op, ' . TABLE_ORDERS_PRODUCTS_DOWNLOAD . ' opd, ' . TABLE_ORDERS_STATUS . ' os ' .
					'where o.customers_id = ' . $accountId . ' and o.orders_id = ' . $orderId . ' and op.orders_products_id = ' . $opId . ' ' .
					'and o.orders_id = op.orders_id and ' .
					'op.orders_products_id = opd.orders_products_id and opd.orders_products_filename != \'\' ' .
					'and o.orders_status = os.orders_status_id and os.downloads_flag = 1 and os.language_id = ' . $language_id;
					$dataReturned2 = mysql_query($sqlQuery2) or die(mysql_error());
					$i2 = 0;
					while($row2 = mysql_fetch_array($dataReturned2))
					{
  						list($dt_year, $dt_month, $dt_day) = explode('-', $row2['date_purchased_day']);
  						$download_timestamp = mktime(23, 59, 59, $dt_month, $dt_day + $row2['download_maxdays'], $dt_year);

						// Continue if time expired (maxdays = 0 means no time limit)
						if (($row2['download_maxdays'] != 0) && ($download_timestamp <= time())) continue;
						// Continue if remaining count is <=0
						if ($row2['download_count'] <= 0) continue;
						// Continue if file is not there
						$filepath = DIR_FS_DOWNLOAD . $row2['orders_products_filename'];
						if (!file_exists($filepath)) continue;
						$value{'OrderComponent'}{$i}{'products'}{$i1}{'downloads'}{$i2}{'id'}= (int)$row2['orders_products_download_id'];

						$i2++;
					}
					$i1++;
				}
				$i++;
			}
			if ($i == 0)
			{
				$value{'OrderComponent'}{0}{'id'}= -10;
			}
		}
		else if ($orderId > 0)
		{
			$value{'OrderComponent'}{0}{'id'}= (int)$orderId;
		}
		return $value;
	}

	function download(&$params) 
	{
		$language_id = (int)$params['languageId'];
		$accountId = (int)$params['accountId'];
		$downloadId = (int)$params['downloadId'];

		$sqlQuery = "select date_format(o.date_purchased, '%Y-%m-%d')" . ' as date_purchased_day, opd.download_count, opd.download_maxdays, opd.orders_products_filename ' . 
		'from ' . TABLE_ORDERS . ' o, ' . TABLE_ORDERS_PRODUCTS . ' op, ' . TABLE_ORDERS_PRODUCTS_DOWNLOAD . ' opd, ' . TABLE_ORDERS_STATUS . ' os ' .
		'where o.customers_id = ' . $accountId . ' and opd.orders_products_download_id = ' . $downloadId . ' ' .
		'and o.orders_id = op.orders_id and ' .
		'op.orders_products_id = opd.orders_products_id and opd.orders_products_filename != \'\' ' .
		'and o.orders_status = os.orders_status_id and os.downloads_flag = 1 and os.language_id = ' . $language_id;
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		while($row = mysql_fetch_array($dataReturned))
		{
			list($dt_year, $dt_month, $dt_day) = explode('-', $row['date_purchased_day']);
			$download_timestamp = mktime(23, 59, 59, $dt_month, $dt_day + $row['download_maxdays'], $dt_year);

			// Continue if time expired (maxdays = 0 means no time limit)
			if (($row['download_maxdays'] != 0) && ($download_timestamp <= time())) continue;
			// Continue if remaining count is <=0
			if ($row['download_count'] <= 0) continue;
			// Continue if file is not there
			$file = DIR_FS_DOWNLOAD . $row['orders_products_filename'];
			if (!file_exists($file)) continue;
			
			// Now decrement counter
	  		$sql = 'update ' . TABLE_ORDERS_PRODUCTS_DOWNLOAD . ' set download_count = download_count-1 where orders_products_download_id = ' . $downloadId;
			mysql_query($sql) or die(mysql_error());

			// Now send the file with header() magic
			
    			header('Content-Description: File Transfer');
    			header('Content-Type: application/octet-stream');
    			header('Content-Disposition: attachment; filename='.basename($file));
    			header('Content-Transfer-Encoding: binary');
    			header('Expires: 0');
    			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    			header('Pragma: public');
    			header('Content-Length: ' . filesize($file));
    			ob_clean();
    			flush();
			
    			readfile($file);

			break;
		}		
	}
}
?>
